package net.xdclass.rbac_shiro.config;

import net.xdclass.rbac_shiro.domain.Role;
import net.xdclass.rbac_shiro.domain.User;
import net.xdclass.rbac_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        User user = userService.findAllUserInfoByUsername(username);
        List<Role> roleList = user.getRoleList();
        Set<String> stringRoleNameSet = roleList.stream().map(role -> role.getName()).collect(Collectors.toSet());
        Set<String> stringPermissionNameList = new HashSet<>();
        roleList.stream().peek(role -> {
            List<String> permissionNameList = role.getPermissionList().stream().map(permission -> {
                String permissionName = permission.getName();
                if (permissionName != null && "".equals(permissionName)) {
                    return permissionName;
                }
                return null;
            }).collect(Collectors.toList());
            stringPermissionNameList.addAll(permissionNameList);
        });

        roleList.forEach(e -> e.getPermissionList());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(stringRoleNameSet);
        simpleAuthorizationInfo.addStringPermissions(stringPermissionNameList);
        return simpleAuthorizationInfo;
    }

    /**
     * 用户登录认证操作
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = userService.findSimpleUserInfoByUsername(username);
        String password = user.getPassword();
        if (password == null || "".equals(password)) return null;

        return new SimpleAuthenticationInfo(username, password, this.getClass().getName());
    }
}
